import 'package:flutter/material.dart';
import 'package:ljy_flutter/provider_mvvm_example/service/joke_service.dart';
import 'package:ljy_flutter/provider_mvvm_example/view/joke_item.dart';
import 'package:ljy_flutter/provider_mvvm_example/view_model/joke_view_model.dart';
import 'package:provider/provider.dart';

class JokeView extends StatefulWidget {
  const JokeView({super.key});

  @override
  State<JokeView> createState() => _JokeViewState();
}

class _JokeViewState extends State<JokeView> {
  @override
  void initState() {
    JokeViewModel jokeViewModel = Provider.of<JokeViewModel>(context, listen: false);
    JokeService.getJokes(jokeViewModel);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('笑话大全'),
      ),
      body: Consumer<JokeViewModel>(builder: (context, viewModel, child) {
        JokeViewModel jokeViewModel = viewModel;
        if (jokeViewModel.loading) {
          return Center(
            child: CircularProgressIndicator(),
          );
        }

        return ListView.separated(
          itemBuilder: (context, index) {
            jokeViewModel.setJoke(jokeViewModel.jokeList![index]);

            return JokeItem(jokeViewModel: jokeViewModel);
          },
          separatorBuilder: (context, index) {
            return Divider(height: 1,);
          },
          itemCount: jokeViewModel.jokeList?.length ?? 0,
        );
      }),
    );
  }
}